<template>
    <el-drawer v-model="visible" title="添加节点" :class="$style['modify-drawer']" size="50%" :close-on-click-modal="false"
        :close-on-press-escape="false" @close="onCancel">
        <div :class="$style['modify-wrapper']">
            <el-form ref="refForm" :model="formModal" label-width="auto" :rules="rules">
                <el-form-item label="审核部门" prop="organization_code">
                    <el-tree-select @node-click="changeOrganizationCode" v-model="formModal.organization_code"
                        :data="organizationTree" :props="{ label: 'name', value: 'code' }" />
                    <!--                    <el-input v-model="formModal.content" class="w-220" placeholder="请输入事件内容"/>-->
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input v-model="formModal.description" class="w-220" placeholder="请输入备注" />
                </el-form-item>

                <el-form-item label="审核中的额外操作" prop="event">
                    <el-select v-model="formModal.actions" multiple placeholder="审核中的额外操作" clearable>
                        <template :key="index" v-for="(opt, index) in actions">
                            <el-option :label="opt.name" :value="opt.code" />
                        </template>
                    </el-select>
                </el-form-item>
                <!--                <template v-if="isCreate">-->
                <el-form-item label="审批通过关联的节点" prop="event">
                    <el-select v-model="formModal.trueEvent" placeholder="通过后的事件类型" clearable>
                        <template :key="index" v-for="(opt, index) in eventOptions">
                            <el-option :label="opt.name" :value="opt.id" />
                        </template>
                    </el-select>
                </el-form-item>

                <!--                    <el-form-item label="通过后的事件内容" prop="content">-->
                <!--                        <el-input v-model="formModal.trueContent" class="w-220" placeholder="请输入通过后的事件内容"/>-->
                <!--                    </el-form-item>-->

                <el-form-item label="驳回申请关联的节点" prop="event">
                    <el-select v-model="formModal.falseEvent" placeholder="未通过的事件类型" clearable>
                        <template :key="index" v-for="(opt, index) in falseEventOptions">
                            <el-option :label="opt.name" :value="opt.id" />
                        </template>
                    </el-select>
                </el-form-item>

                <!--                    <el-form-item label="未通过的事件内容" prop="content">-->
                <!--                        <el-input v-model="formModal.falseContent" class="w-220" placeholder="请输入未通过的事件内容"/>-->
                <!--                    </el-form-item>-->
                <!--                </template>-->
            </el-form>

            <div :class="$style['button-wrapper']">
                <el-button @click="onCancel">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onSubmit">保存</el-button>
                <!--                <el-button type="primary" @click="onTest(1)">测试失败直接结束</el-button>-->
                <!--                <el-button type="primary" @click="onTest(2)">测试失败有节点</el-button>-->
            </div>
        </div>
    </el-drawer>
</template>

<script setup name="DrawerModifyJudgment">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useInject } from '@/utils/workflow/workflow.event'
// import {OrganizationApi} from "@/api/organization.js";
// import {WorkflowApi} from "@/api/workflow.js";

// 从 useInject 中获取需要的方法
const { appendJudgment, modifyJudgment } = useInject()

const refForm = ref(null) // 表单引用
const visible = ref(false) // 控制 Drawer 显示状态
const loading = ref(false) // 控制加载状态
const isCreate = ref(true) // 判断是创建还是修改
let currentType // 当前事件类型

// 表单数据模型
const formModal = reactive({
    organization_code: '',
    description: '',
    actions: [],
    content: '',
    trueEvent: '',
    trueContent: '',
    falseEvent: '',
    falseContent: ''
})

// 节点数据
const assignData = reactive({
    from: [],
    to: []
})
// 校验规则
const rules = reactive({
    organization_code: { required: true, message: '请选择审核部门', trigger: 'change' },
    description: { required: true, message: '请输入备注', trigger: 'blur' },
    trueEvent: { required: true, message: '请选择通过后的事件', trigger: 'change' },
    trueContent: { required: true, message: '请输入通过后事件内容', trigger: 'blur' },
    falseEvent: { required: true, message: '请选择通过后的事件', trigger: 'change' },
    falseContent: { required: true, message: '请输入通过后事件内容', trigger: 'blur' }
})
// 事件选项
const eventOptions = [
    { id: '-1', category: 'end', name: '标记结束', icon: '&#xe622;' },
    { id: '0', category: 'IF_NODE', name: '判断节点', icon: '&#xe623;' },
    // {id: '1', category: 'evnet2', name: '事件2', icon: '&#xe62f;'},
    // {id: '2', category: 'evnet3', name: '事件3', icon: '&#xe625;'},
    // {id: '3', category: 'evnet4', name: '事件4', icon: '&#xe622;'}
]

// 包含结束标记的事件选项
const falseEventOptions = [
    ...eventOptions,

]

// 取消并关闭 Drawer
const onCancel = () => {
    visible.value = false
    loading.value = false
    formModal.value = {}
}

// 提交表单数据
const onSubmit = () => {
    if (!refForm.value) return

    refForm.value.validate((valid) => {
        if (!valid) return

        const trueEventOption = eventOptions.find(opt => opt.id === formModal.value.trueEvent)
        const falseEventOption = falseEventOptions.find(opt => opt.id === formModal.value.falseEvent)

        if (isCreate.value) {
            appendJudgment({
                data: { content: formModal.value.content },
                trueData: {
                    id: formModal.value.trueID,
                    event: formModal.value.trueEvent,
                    category: trueEventOption?.category,
                    icon: trueEventOption?.icon,
                    title: trueEventOption?.name,
                    content: formModal.value.trueContent
                },
                falseData: {
                    id: formModal.value.falseID,
                    event: formModal.value.falseEvent,
                    category: falseEventOption?.category,
                    icon: falseEventOption?.icon,
                    title: falseEventOption?.name,
                    content: formModal.value.falseContent,
                },
                from: assignData.from,
                to: assignData.to
            })
        } else {
            modifyJudgment({
                id: formModal.value.id,
                data: { description: formModal.value.description }
            })
        }

        ElMessage.success(isCreate.value ? '创建成功' : '更新成功')
        onCancel()
    })
}

// 打开 Drawer 并初始化数据
const open = ({ type, id, data = {}, from, to }) => {
    console.log('🚀 ~ open ~ type, id, data, from, to:', type, id, data, from, to)

    currentType = 'appendJudgment' // 设置当前类型
    isCreate.value = id === undefined

    formModal.value = {
        id,
        content: data.content,
        organization_code: data.organization_code,
        description: data.description,
        actions: data.actions,
        trueID: data.trueID,
        trueEvent: data.trueEvent,
        trueContent: '111',
        falseID: data.falseID,
        falseEvent: data.falseEvent,
        falseContent: '222'
    }
    // console.log(formModal.value)
    assignData.from = Array.isArray(from) ? from : [from]
    assignData.to = Array.isArray(to) ? to : [to]

    visible.value = true
}

// 测试函数
const onTest = (type) => {
    let falseData = {}
    switch (type) {
        case 1:
            falseData = { category: 'end' }
            break
        case 2:
            falseData = {
                event: '1',
                category: 'evnet2',
                title: '事件2',
                icon: '&#xe62f;',
                content: '2222'
            }
            break
        default:
            break
    }
}

const organizationTree = ref([])

const loadOrganizationTree = async () => {
    try {
        // organizationTree.value = await OrganizationApi().getTree().then(res => formatTreeData(res))
        organizationTree.value = []
    } catch (xhr) {
        organizationTree.value = []
    }
}

const actions = ref([])
const loadAction = async () => {
    try {
        // actions.value = await WorkflowApi().action().then(res => formatTreeData(res))
        actions.value = []
    } catch (xhr) {
        actions.value = []
    }
}

const formatTreeData = (data) => {
    const loop = (item) => {
        item.disabled = !!item.disabled

        if (Array.isArray(item.children) && item.children.length) {
            item.children = item.children.map(child => loop(child))
        }

        return item
    }

    const list = data?.map(item => {
        return loop(item)
    }) || []

    return list
}

const changeOrganizationCode = (data, node) => {
    formModal.value.content = data.name
}


onMounted(() => {
    loadOrganizationTree()
    loadAction()
})

defineExpose({
    open
})
</script>

<style lang="scss" module>
.modify-drawer {
    @include defineEl('drawer__header') {
        margin-bottom: 0;
    }

    @include defineEl('drawer__body') {
        --el-drawer-padding-primary: 20px 20px 10px;
    }
}

.modify-wrapper {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.table-wrapper {
    flex: 1;
    height: 0;
}

.button-wrapper {
    display: flex;
    justify-content: right;
    align-items: center;
    padding-top: 10px;
}
</style>